<?php
/**
 * User: 784855684@qq.com
 * Date: 31/12/2017
 * Time: 20:14
 */
declare(strict_types=1);


namespace AppBundle\Utils;


use AppBundle\Entity\Material;
use AppBundle\Entity\MaterialOrder;

class MaterialOrderUtil extends EntityUtil
{
    /**
     * @param Material $material
     * @param int $number
     * @param bool $autoFlush
     * @return MaterialOrder
     */
    public function create(Material $material, int $number, bool $autoFlush = true): MaterialOrder
    {
        $order = new MaterialOrder();
        $order->setNumber($number);
        $order->setCreateAt(new \DateTime());
        $order->setMaterial($material);

        $this->em->persist($order);
        $autoFlush and $this->em->flush();
        return $order;
    }

    /**
     * @param MaterialOrder $order
     * @param bool $autoFlush
     * @param bool $useTransaction
     * @return void
     * @throws \Doctrine\DBAL\ConnectionException
     */
    public function finish(MaterialOrder $order, bool $autoFlush = true, bool $useTransaction = true)
    {
        if ($autoFlush and $useTransaction) $this->em->getConnection()->beginTransaction();
        $material = $order->getMaterial();
        $order->setFinishAt(new \DateTime());
        $material->setInventory($material->getInventory() + $order->getNumber());
        $autoFlush and $this->em->flush();
        if ($autoFlush and $useTransaction) $this->em->getConnection()->commit();
    }

}